

package jetbrains.buildServer.server.rest.jersey;

import com.sun.jersey.spi.container.*;
import java.io.IOException;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.Provider;
import jetbrains.buildServer.util.Disposable;
import jetbrains.buildServer.util.NamedDaemonThreadFactory;
import org.springframework.stereotype.Component;

@Provider
@Consumes
@Produces
@Component
public class ThreadNamingContainerResponseFilter implements ContainerResponseFilter {
  @Override
  public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
    return new ThreadNamingContainerResponse(response);
  }

  public class ThreadNamingContainerResponse extends AdaptingContainerResponse {
    public ThreadNamingContainerResponse(ContainerResponse delegate) {
      super(delegate);
    }

    @Override
    public void write() throws IOException {
      Disposable threadName = NamedDaemonThreadFactory.patchThreadName("Serializing REST response");
      try {
        super.write();
      } finally {
        threadName.dispose();
      }
    }
  }
}